const router = require('koa-router')()
const cc = require('../conCtl')
const js = require('../jsCtl')
const db = require('../dbCtl')
const pc = require('../projectCtl');

/**
@hostpath = http://127.0.0.1/client/game
 */

/** 前端请求抽奖数据
###
    GET {{hostpath}}/queue/1
### */
router.get('/queue/:game_id', async c => {
    let data = pc.storeDial.gameList[c.params.game_id].users;
    cc.send(c, data);
});

/** 获取所有活动列表
###
    GET {{hostpath}}
### */
router.get('/', async c => {
    let data = await db.start('select * from ( ' +
        'SELECT 1 AS `type`, id, `name`,img, dt FROM t_gameLottery WHERE state=2 ' +
        'UNION ' +
        'SELECT 2 AS `type`, id, `name`,img, dt FROM t_gameDial WHERE state=2 ' +
        ') a ORDER BY dt');

    cc.send(c, data);
});

/** 获取指定活动信息
###
    GET {{hostpath}}/lottery/1
### */
router.get('/lottery/:id', async c => {
    let data = await db.model('t_gameLottery').where('id=?&&state=2', c.params.id).shift('未找到活动');
    let model_prize = await db
        .model('t_gameLottery_prize a').join('t_goods b on a.goods_id=b.id')
        .field('a.goods_id, a.prize_level, a.show_amount, b.name, b.intro, b.details, b.market_price')
        .where('a.game_id=?&&b.state>0', data.id)
        .orderBy('a.prize_level, a.dt')
        .select();
    data.prizes = model_prize;

    cc.send_list(c, data);
});

/** 获取九宫格活动信息
###
    GET {{hostpath}}/dial/1
### */
router.get('/dial/:id', async c => {
    let moment = require('moment');
    let data = {};
    let queue = pc.storeDial.gameList[c.params.id];//队列
    data = js.cloneObject(queue);
    // cc.log(data);return;
    if (!js.isNullOrUndefined(data)) {
        data.info.dt1 = moment.unix(data.info.dt1).format('YYYY-MM-DD HH:mm:ss');
        data.info.dt2 = moment.unix(data.info.dt2).format('YYYY-MM-DD HH:mm:ss');
        for (let i = 0; i < data.prizes.length; i++) {
            const element = data.prizes[i];
            // element.details = await db.model('t_goods').where('id=?', element.goods_id).shift('', 'details');
            // element.name = await db.model('t_goods').where('id=?', element.goods_id).shift('', 'name');
            element.details = element.details.split(';')[0];
            // element.market_price = await db.model('t_goods').where('id=?', element.goods_id).shift('', 'market_price');
            data.prizes[i] = js.regroup(element, ['details', 'market_price', 'game_id', 'goods_id', 'name', 'amount', 'prize_id', 'prize_level', 'state'])
        }
    }
    // let data = await db.model('t_gameDial').where('id=?&&state=2', c.params.id).shift('未找到活动');
    // data.dt1 = moment.unix(data.dt1).format('YYYY-MM-DD HH:mm:ss');
    // data.dt2 = moment.unix(data.dt2).format('YYYY-MM-DD HH:mm:ss');
    // let model_prize = await db
    //     .model('t_gameDial_prize a').join('t_goods b on a.goods_id=b.id')
    //     .field('a.goods_id, a.prize_level, b.`name`, b.intro, b.details, b.market_price')
    //     .where('a.game_id=?', data.id)
    //     .select();
    // for (let i = 0; i < model_prize.length; i++) {
    //     const element = model_prize[i];
    //     element.details = element.details.split(';')[0];
    // }
    // data.prizes = model_prize;


    cc.send_list(c,data);
});

/** 获取定期抽奖活动中，用户奖票数量
###
    GET {{hostpath}}/lottery/3/oM2uY59aMmztLxDeqN2hC8fcCo8c
### */
router.get('/lottery/:id/:openid', async c => {
    let data = await db.model('t_gameLottery_ticket')
        .field('count(1) as c')
        .where('game_id=?&&openid=?', c.params.id, c.params.openid)
        .shift();

    cc.send(c, data);
});

/** 使用积分购买活动奖票
###
    POST {{hostpath}}/lotteryPrice/3/oM2uY59aMmztLxDeqN2hC8fcCo8c
### */
router.post('/lotteryPrice/:id/:openid', async c => {
    let game = await db.model('t_gameLottery').where('id=?', c.params.id).shift('未找到活动');
    let lotteryName = game.name;
    let lotteryPrice = game.price;
    if (!js.compareDate(game.dt1)) js.throwObj('活动报名已截止');
    let userPoints = await db.model('t_users').field('points').where('openid=?', c.params.openid).shift('未找到用户', 'points');
    if (userPoints < lotteryPrice) js.throwObj('珠珠币不足', js.rescode.fail);

    //获取购票总数
    let ticketCount = await db.model('t_gameLottery_ticket').where('game_id=?', c.params.id).count('购票');
    if (game.circulation <= ticketCount) js.throwObj('活动奖票已售空');

    await db.startTransaction(async (tran) => {
        await tran.model('t_users').where('openid=?', c.params.openid).update({ points: userPoints - lotteryPrice });
        await tran.model('t_gameLottery_ticket').insert({ game_id: c.params.id, openid: c.params.openid });
        await tran.model('t_points_log').insert({ openid: c.params.openid, direction: 1, type: 0, pointsValue: -1 * lotteryPrice, remark: `购买${lotteryName}活动奖票` });
    })

    cc.send(c);
});

/** 使用奖票购买活动奖票
###
    POST {{hostpath}}/lotteryTicket/1/test
    Content-Type: application/json
### */
router.post('/lotteryTicket/:id/:openid', async c => {
    let userTicket = await db.model('t_users').where('openid=?', c.params.openid).shift('未找到用户', 'lottery_ticket');

    if (userTicket < 1) js.throwObj('用户奖票不足', js.rescode.fail);

    let game = await db.model('t_gameLottery').where('id=?', c.params.id).shift('未找到活动');
    if (!js.compareDate(game.dt1)) js.throwObj('活动报名已截止');
    let ticketCount = await db.model('t_gameLottery_ticket').where('game_id=?', c.params.id).count('购票');
    if (game.circulation <= ticketCount) js.throwObj('活动奖票已售空');

    await db.startTransaction(async (tran) => {
        await tran.model('t_users').where('openid=?', c.params.openid).update({ lottery_ticket: userTicket - 1 });
        await tran.model('t_gameLottery_ticket').insert({ game_id: c.params.id, openid: c.params.openid });
    })

    cc.send(c);
});


/** 九宫格立即抽奖
###
    POST {{hostpath}}/partake
    Content-Type: application/json

    {
        "game_id":"1",
        "openid":"oM2uY59aMmztLxDeqN2hC8fcCo8c"
    }
### */
router.post('/partake', async c => {
    js.check_params(
        !c.request.body.game_id && '!活动' ||
        !c.request.body.openid && '!用户信息');
    //获取活动数据
    let game = await db.model('t_gameDial').where('id=?&&state=2', c.request.body.game_id).shift('未找到活动');
    let time = Date.parse(new Date()) / 1000;
    if (game.dt1 > time) js.throwObj('活动未开始');
    if (game.dt2 < time) js.throwObj('活动参与已截止!');
    let user = await db.model('t_users').where('openid=?', c.request.body.openid).shift('为找到用户');
    if (user.points < game.price) js.throwObj('您的珠珠币不足,请先充值!', js.rescode.low_score);

    await db.model('t_users').where('openid=?', c.request.body.openid).update({ points: user.points - game.price });//修改用户珠珠币

    let queue_id = await db.model('t_gameDial_queue').insert({ game_id: c.request.body.game_id, openid: c.request.body.openid, dt: time });//加入队列数据表
    let queue = await db.model('t_gameDial_queue a').field('1 as type,a.*,b.*').join('t_users b on a.openid=b.openid').where('id=?', queue_id).shift();
    pc.storeDial.gameList[c.request.body.game_id].users.push(queue);//将新参加抽奖的用户加入九宫格抽奖缓存队列
    cc.send(c);
});



module.exports = router